<?php


namespace app\admin\controller;


use app\model\BottomMenu;
use app\model\UserMenu;
use think\exception\ValidateException;

class UsermenuController extends Base
{
    public function index(){
        $uniacid = uniacid();

        $keyword = input('post.keyword', '', 'serach_in');
        $mo = input('post.mo', '', 'serach_in');

        $query = UserMenu::where(['uniacid'=>$uniacid]);

        if(!empty($keyword)){
            $query->where('title', 'like', '%' . $keyword . '%');
        }

        if(!empty($mo)){
            $query->where('mo',$mo);
        }

        $res = $query->order('sort asc,id asc')->select()->toArray();

        foreach ($res as &$v){
            $v['mo'] = UserMenu::$mo[$v['mo']];
            $v['plugin'] = UserMenu::$plugins[$v['plugin']];
        }

        return $this->json(['data'=>$res]);
    }

    function listUpdate()
    {
        $data = only('id,status,sort');
        if (!$data['id']) throw new ValidateException('参数错误');
        UserMenu::update($data);
        return $this->json(['msg' => '操作成功']);
    }

    public function update()
    {
        $id = $this->request->post('id');
        $data = input('post.');

        if (empty($id)) {
            $data['uniacid'] = uniacid();

            try {
                $res = UserMenu::create($data);
                if ($res->id && empty($data['sort'])) {
                    UserMenu::update(['sort' => $res->id, 'id' => $res->id]);
                }
            } catch (\Exception $e) {
                throw new ValidateException($e->getMessage());
            }

            return $this->json(['msg' => '添加成功', 'data' => $res->id]);
        } else {

            try {
                UserMenu::update($data);
            } catch (\Exception $e) {
                throw new ValidateException($e->getMessage());
            }
            return $this->json(['msg' => '修改成功']);
        }
    }

    function getInfo()
    {
        $id =  $this->request->post('id', '', 'serach_in');
        if (!$id) throw new ValidateException('参数错误');
        $data = UserMenu::field('*')->find($id)->toArray();

        return $this->json(['data' => $data]);
    }

    function delete()
    {
        $idx =  $this->request->post('id', '', 'serach_in');
        if (!$idx) throw new ValidateException('参数错误');
        UserMenu::destroy(['id' => explode(',', $idx)], true);
        return $this->json(['msg' => '操作成功']);
    }
}
